#include "login_ecgeeg.h"
#include "ui_login_ecgeeg.h"
#include "db/mysql.h"
#include "cglobal.h"
#include "QJsonObject"
#include "QJsonArray"
#include "QJsonDocument"
#include <QRegularExpression>
#include "QFile"
Login_ECGEEG::Login_ECGEEG(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Login_ECGEEG)
{
    ui->setupUi(this);
    isfirst=true;
    initWindowsSet();//窗口属性设置
    initTableWidget();//初始化任务列表
    initTableWidget_sel();
    initSettings();//初始化设置选项
    MultiUSBDongleAPI_Init();//API初始化设置
    initControls();//控件属性设置
    initSerialPort();//初始化串口
    initVariables();//初始化一些控制变量
    initTimers();//初始化定时器
    initViedo();//初始化视频
    initRealWaveCharts();//初始化实时波形图设置
    init3DFFT();//初始化3dfft频谱图



}

Login_ECGEEG::~Login_ECGEEG()
{
    // if(serialPort->isOpen())
    // {
    //     timer.start();//用于关闭数据传输
    // }
    // disconnect(&timer,SIGNAL(timeout()),this,SLOT(stopTrans()));
    // timerRealTimeIndex.stop();
    // disconnect(&timerRealTimeIndex,SIGNAL(timeout()),this,SLOT(updateIndex()));
    // delete serialPort;
    // delete container;
    // delete m_graph;
    // delete modifier;

    delete settings;
    delete ui;
}
void Login_ECGEEG::initWindowsSet()
{
    setWindowTitle(tr("基于心电和脑电数据采集分析实验平台"));//可执行程序标题
    setWindowIcon(QIcon(":/new/prefix1/images/logo.png"));//可执行程序图标
    this->setWindowFlags(Qt::Dialog|Qt::FramelessWindowHint);
}
void Login_ECGEEG::initVariables()
{
    isBind=false;
    isClear=false;
    StartCollectFlag=false;
    isSaveRawData=true;
    stopNum=0;
    SampleNum=0;
    isExitCollect=false;
}

void Login_ECGEEG::init3DFFT()
{
    //3Dfft频谱图
    m_graph = new Q3DSurface();
    container = QWidget::createWindowContainer(m_graph);
    ui->horizontalLayout_fft->addWidget(container,1);
    modifier = new SurfaceGraphModifier(m_graph);
    // 3Dfft波形图显示方式
    QObject::connect(ui->gradientBtoYPB, &QPushButton::pressed,modifier, &SurfaceGraphModifier::setBlackToYellowGradient);
    QObject::connect(ui->gradientGtoRPB, &QPushButton::pressed,modifier, &SurfaceGraphModifier::setGreenToRedGradient);
    setFFTColorModel();
}
void Login_ECGEEG::initSerialPort()
{
    //串口
    serialPort=new QSerialPort();
    connect(serialPort,SIGNAL(readyRead()),this,SLOT(readComDataSlot()));
    ui->pb_OpenSerial->setText("刷新串口");
    refresh_serial();
}
void Login_ECGEEG::initTimers()
{
    //timer 用于控制发送停止指令，两个设备的停止指令不能连续发送，需要间隔一段时间发送
    timer.setInterval(100);
    connect(&timer,SIGNAL(timeout()),this,SLOT(stopTrans()));

    connect(&timerRealTimeIndex,SIGNAL(timeout()),this,SLOT(updateIndex()));
    connect(&timerFFT3DAnaShow,SIGNAL(timeout()),this,SLOT(onFFTAnaShow()));
    timerForStep.setInterval(1000);
    connect(&timerForStep,SIGNAL(timeout()),this,SLOT(onStepShow()));
    timer_DeviceState.setInterval(400);
    connect(&timer_DeviceState,SIGNAL(timeout()),this,SLOT(updateDeviceState()));
    connect(ui->tabWidget, &QTabWidget::currentChanged, this, &Login_ECGEEG::onTabChanged);
}

void Login_ECGEEG::onTabChanged(int index) {
    QWidget *currentWidget = ui->tabWidget->widget(ui->tabWidget->currentIndex());
    QWidget *nextWidget = ui->tabWidget->widget(index);
    if (currentWidget && nextWidget) {
        if(ui->radioButton_2->isChecked()){
        // 创建动画
            QPropertyAnimation *animation = new QPropertyAnimation(nextWidget, "geometry");
            animation->setDuration(300); // 动画时长 100 毫秒
            // 设置动画起始和结束位置
            QRect startRect = nextWidget->geometry();
            startRect.moveLeft(ui->tabWidget->width());  // 从右侧进入
            animation->setStartValue(startRect);
            animation->setEndValue(nextWidget->geometry());
            // 启动动画
            animation->start(QAbstractAnimation::DeleteWhenStopped);
        }else if(ui->radioButton_4->isChecked())
        {
            QGraphicsOpacityEffect *effectOut = new QGraphicsOpacityEffect(currentWidget);
            currentWidget->setGraphicsEffect(effectOut);
            QPropertyAnimation *animationOut = new QPropertyAnimation(effectOut, "opacity");
            animationOut->setDuration(300);
            animationOut->setStartValue(1.0);
            animationOut->setEndValue(0.0);

            // 创建淡入动画
            QGraphicsOpacityEffect *effectIn = new QGraphicsOpacityEffect(nextWidget);
            nextWidget->setGraphicsEffect(effectIn);
            QPropertyAnimation *animationIn = new QPropertyAnimation(effectIn, "opacity");
            animationIn->setDuration(300);
            animationIn->setStartValue(0.0);
            animationIn->setEndValue(1.0);

            // 启动动画
            animationOut->start(QAbstractAnimation::DeleteWhenStopped);
            animationIn->start(QAbstractAnimation::DeleteWhenStopped);
        }else if(ui->radioButton_3->isChecked())
        {
            // 创建动画
            QPropertyAnimation *animation = new QPropertyAnimation(nextWidget, "geometry");
            animation->setDuration(300); // 动画时长 300 毫秒

            // 设置动画起始和结束位置
            QRect startRect = nextWidget->geometry();
            startRect.moveTop(ui->tabWidget->height());  // 从底部进入
            animation->setStartValue(startRect);
            animation->setEndValue(nextWidget->geometry());

            // 启动动画
            animation->start(QAbstractAnimation::DeleteWhenStopped);
        }

    }
}
void Login_ECGEEG::initControls()
{
    ui->tabWidget->setCurrentIndex(0);//默认在登录页面
    ui->tabWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    ui->lineEdit_age->setValidator(new QIntValidator(10,99,this));  // [10,99]范围内的整数输入
    //限制3Dfft频谱图自动调整最大最小值只能输入数字
    ui->lineEdit_maxY->setValidator(new QDoubleValidator());
    ui->lineEdit_minY->setValidator(new QDoubleValidator());
    //串口打开成功或者失败图标显示
    ui->label_serialportstate->setScaledContents(true);
    ui->label_serialportstate->setStyleSheet(QString("border-image:url(:/new/prefix1/images/msg_error.png);"));




    ui->checkBox_video->setChecked(true);//默认选择视频资源
    // 默认自动调整3D频谱图
    isAutoAdjugeY=true;
    // ui->checkBox_AdjustY->setChecked(true);

    ui->checkBox_video_len->setChecked(true);
    ui->comboBox_videotimeSet->setEnabled(false);
    ui->horizontalSlider_volume->setRange(0,100);

    ui->horizontalSlider_volume->setValue(50);
    ui->progressBar_ecg_ele->setValue(0);
    ui->progressBar_eeg_ele->setValue(0);
    ui->progressBar_ecg_ele->setMaximum(100);
    ui->progressBar_ecg_ele->setMinimum(0);
    ui->progressBar_eeg_ele->setMaximum(100);
    ui->progressBar_eeg_ele->setMinimum(0);

    ui->radioButton->setChecked(true);

    ui->checkBox_saveRawData->setChecked(true);
    ui->lineEdit_SaveDataPath->setText(settings->value("SaveRawPath").toString());
    ui->progressBar->setValue(0);
}

QList<DesignData> Login_ECGEEG::getDesignData(QString s)
{
    QJsonDocument jsonDoc = QJsonDocument::fromJson(s.toUtf8());
    QJsonObject job=jsonDoc.object();
    QList<DesignData> dds;
    if(job.contains("jsonArray") && job.value("jsonArray").isArray())
    {
        QJsonArray ja=job.value("jsonArray").toArray();
        for(int i=0;i<ja.size();i++)
        {
            DesignData dd;
            QJsonObject jo1=ja.at(i).toObject();
            if(jo1.contains("Type")&& jo1.value("Type").isString())
                dd.Type=jo1.value("Type").toString();
            if(jo1.contains("Time")&& jo1.value("Time").isString())
                dd.durationtimes=jo1.value("Time").toString();
            if(jo1.contains("Path")&& jo1.value("Path").isString())
                dd.resourcePath=jo1.value("Path").toString();
            if(jo1.contains("SourceType")&& jo1.value("SourceType").isString())
                dd.resourceType=jo1.value("SourceType").toString();
            dds.append(dd);
        }

    }
    return dds;
}
void Login_ECGEEG::MultiUSBDongleAPI_Init()
{
    MultiUSBDongle_init();
    MultiUSBDongle_getBioEEGOXDevice_StartCollectionOrder(dualeegStartCollectOrder);
    MultiUSBDongle_getBioEEGOXDevice_StopCollectionOrder(dualeegStopCollectOrder);
    MultiUSBDongle_getECG_Holter_Device_StartCollectionOrder(ecgHolterStartCollectOrder);
    MultiUSBDongle_getECG_Holter_Device_InfoOrder(ecgHolterInfoOrder);
    MultiUSBDongle_getECG_Holter_Device_StopCollectionOrder(ecgHolterStopCollectOrder);
    QByteArray ecgMac=Hexstring2QByteArray(ui->lineEdit_ECGMac->text());
    QByteArray dualeegMac=Hexstring2QByteArray(ui->lineEdit_DualEEGMac->text());

    MultiUSBDongle_setECG_HolterMac(reinterpret_cast<unsigned char*>(ecgMac.data()));
    MultiUSBDongle_setDualEEGMac(reinterpret_cast<unsigned char*>(dualeegMac.data()));

}
void Login_ECGEEG::initRealWaveCharts()
{
    mpcs_ir=new MeasurePageCharts(500,"红外脉搏波");
    mpcs_ecg=new MeasurePageCharts(500,"心电ECG");
    mpcs_resp=new MeasurePageCharts(500,"呼吸波");
    mpcs_eeg=new MeasurePageCharts(500,"脑电波");
    ir_Chart=mpcs_ir->CreateLineChart();
    ecg_Chart=mpcs_ecg->CreateLineChart();
    resp_Chart=mpcs_resp->CreateLineChart();
    eeg_Chart=mpcs_eeg->CreateLineChart();
    // mpcs_tempture->setWaveyRanger(20,40);
    ui->widget_ppg->setChart(ir_Chart);
    ui->widget_ecg->setChart(ecg_Chart);
    ui->widget_resp->setChart(resp_Chart);
    ui->widget_eeg->setChart(eeg_Chart);
    ui->widget_resp->setRenderHint(QPainter::Antialiasing);
    ui->widget_eeg->setRenderHint(QPainter::Antialiasing);
    ui->widget_ecg->setRenderHint(QPainter::Antialiasing);
    ui->widget_ppg->setRenderHint(QPainter::Antialiasing);

}
void Login_ECGEEG::initViedo()
{
    m_pPlayer = new QMediaPlayer(this);
    m_pPlayerWidget = new QVideoWidget(ui->label_vidio);
    audioOutput=new QAudioOutput(this);
    m_pPlayerWidget->resize(1536,800);
    m_pPlayer->setVideoOutput(m_pPlayerWidget);
    audioOutput->setVolume(0.5f);
    m_pPlayer->setVideoOutput(m_pPlayerWidget);
    m_pPlayer->setLoops(5);
    m_pPlayer->setAudioOutput(audioOutput);
    connect(m_pPlayer,SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),this,SLOT(Mplayer_State(QMediaPlayer::MediaStatus)));
    connect(m_pPlayer, SIGNAL(durationChanged(qint64)), this, SLOT(OnDurationChanged(qint64)));
    connect(m_pPlayer, SIGNAL(positionChanged(qint64)), this, SLOT(OnSlider(qint64)));
}
void Login_ECGEEG::initSettings()
{
    settings=new QSettings(QSettings::NativeFormat, QSettings::UserScope, QCoreApplication::organizationName(), QCoreApplication::applicationName());
    // ui->lineEdit_DualEEGMac->setText(settings->value("DUALEEGMAC").toString());
    // ui->lineEdit_OxBracketMac->setText(settings->value("OXBRACKETMAC").toString());
    // ui->lineEdit_ECGMac->setText(settings->value("ECGHOLTERMAC").toString());
    // ui->comboBox_realtimeAnaSet->setCurrentIndex(settings->value("realtimeAnaInterval").toInt()/1000-1);
    ui->comboBox_realtimeAnaSet->setCurrentIndex(3);
    // timerRealTimeIndex.setInterval(settings->value("realtimeAnaInterval").toInt());
    timerRealTimeIndex.setInterval(1000);
    ui->comboBox_ffttimeSet->setCurrentIndex(settings->value("ffttimeAnaInterval").toInt()/1000-1);
    timerFFT3DAnaShow.setInterval(settings->value("ffttimeAnaInterval").toInt());
    timerFFT3DAnaShow.setInterval(3000);

}
void Login_ECGEEG::setFFTColorModel()
{
    QLinearGradient grBtoY(0, 0, 1, 100);
    grBtoY.setColorAt(1.f, Qt::black);
    grBtoY.setColorAt(0.67f, Qt::blue);
    grBtoY.setColorAt(0.33f, Qt::red);
    grBtoY.setColorAt(0.f, Qt::yellow);
    QPixmap pm(24, 100);
    QPainter pmp(&pm);
    pmp.setBrush(QBrush(grBtoY));
    pmp.setPen(Qt::NoPen);
    pmp.drawRect(0, 0, 24, 100);

    ui->gradientBtoYPB->setIcon(QIcon(pm));
    ui->gradientBtoYPB->setIconSize(QSize(24, 100));

    QLinearGradient grGtoR(0, 0, 1, 100);
    grGtoR.setColorAt(1.f, Qt::darkGreen);
    grGtoR.setColorAt(0.5f, Qt::yellow);
    grGtoR.setColorAt(0.2f, Qt::red);
    grGtoR.setColorAt(0.f, Qt::darkRed);
    pmp.setBrush(QBrush(grGtoR));
    pmp.drawRect(0, 0, 24, 100);
    ui->gradientGtoRPB->setIcon(QIcon(pm));
    ui->gradientGtoRPB->setIconSize(QSize(24, 100));
}

QByteArray Login_ECGEEG::Hexstring2QByteArray(QString str)
{
    QByteArray Hexstr;
    bool ok;
    for (int i = 0; i < str.size(); i += 2)
    {
        Hexstr.append((char)str.mid(i, 2).toInt(&ok, 16));
    }
    return Hexstr;
}
void Login_ECGEEG::refresh_serial() //刷新串口按钮槽函数
{
    QStringList comname; //活动串口表
    comname.clear();
    ui->comboBox_serialPort->clear();
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        if(info.productIdentifier()==0x6001 && info.vendorIdentifier()==0x0403){
            comname.append(info.portName());
            ui->pb_OpenSerial->setText("打开串口");
        }
    }
    ui->comboBox_serialPort->addItems(comname);
}
void Login_ECGEEG::on_login_bt_login_clicked()
{
    if(ui->lineEdit->text().length()>0 && ui->lineEdit_age->text().length()>0)
    {
        MultiUSBDongle_setBioEEGOXDevice_UserInfo(ui->lineEdit_age->text().toInt(),ui->comboBox->currentIndex());
        ui->tabWidget->setCurrentIndex(1);
    }else{
        QMessageBox::about(this,"温馨提示","用户名和年龄不能为空！！！");
    }
}

void Login_ECGEEG::on_pb_dataCollect_clicked()
{
    if(serialPort->isOpen()){
        setConnectState(ui->label_ecg_state,false);
        setConnectState(ui->label_eeg_state,false);
        ui->tabWidget->setCurrentIndex(2);
        ui->pb_datacollect_start->setEnabled(false);
    }else{
        on_pb_option_clicked();
    }
}


void Login_ECGEEG::on_pb_homepage_return_clicked()
{
    StartCollectFlag=false;
    ui->tabWidget->setCurrentIndex(0);
}


void Login_ECGEEG::on_pb_history_clicked()
{
    MultiUSBDongle_close();
    ui->tabWidget->setCurrentIndex(3);
    MultiUSBDongleAPI_Init();

}


void Login_ECGEEG::on_pb_design_clicked()
{
    ui->tabWidget->setCurrentIndex(4);
}


void Login_ECGEEG::on_pb_option_clicked()
{
    ui->tabWidget->setCurrentIndex(5);
    MySql *mysql=new MySql(cglobal::DataBasePath);
    ui->comboBox_designsele->clear();
    QList<designDataBean> ddbs=mysql->QueryAllDesignData();
    int ddbs_len=ddbs.size();
    if(ddbs_len>0)
    {
        for(int i=0;i<ddbs_len;i++)
        {
            designDataBean ddb=ddbs.at(i);
            ui->comboBox_designsele->addItem(ddb.name);
        }
        QList<DesignData> dds=getDesignData(ddbs.at(0).content);//显示最近创建的任务
        int len=dds.size();

        int rowCount = m_pTableModel_sel->rowCount();
        if (rowCount > 0)
            m_pTableModel_sel->removeRows(0, rowCount); // 从第 0 行开始删除所有行
        // m_pTableModel->clear();
        totalTime=0;
        stepTimeDuration.clear();resourcePath.clear();switchFlag.clear();eveyStepTime.clear();
        for(int k=0;k<len;k++)
        {
            m_pTableModel_sel->insertRow(k, QModelIndex());
            m_pTableModel_sel->setData(m_pTableModel_sel->index(k, COLUMN_NO), k+1);
            m_pTableModel_sel->setData(m_pTableModel_sel->index(k, COLUMN_TYPE), dds.at(k).Type);

            m_pTableModel_sel->setData(m_pTableModel_sel->index(k, COLUMN_TIME), dds.at(k).durationtimes);
            int c_steptime=convertTimeStringToSeconds(dds.at(k).durationtimes);
            totalTime+=c_steptime;
            stepTimeDuration.push_back(totalTime);
            eveyStepTime.push_back(c_steptime);
            m_pTableModel_sel->setData(m_pTableModel_sel->index(k, COLUMN_PATH), dds.at(k).resourcePath);
            resourcePath.push_back(dds.at(k).resourcePath);
            m_pTableModel_sel->setData(m_pTableModel_sel->index(k, COLUMN_SOURCETYPE), dds.at(k).resourceType);
            if(dds.at(k).resourceType=="视频")
                switchFlag.push_back(1);
            else if(dds.at(k).resourceType=="音频")
                switchFlag.push_back(2);
            else
                switchFlag.push_back(0);
            // 设置全部列居中显示
            for(int j = 0; j < 5; j++)
            {
                m_pTableModel_sel->item(k, j)->setTextAlignment(Qt::AlignCenter);
            }
        }
        // modifier->initData(totalTime/(ui->comboBox_ffttimeSet->currentIndex()+1)+1);
        // modifier->setAxisZRange(0.0f,totalTime/(ui->comboBox_ffttimeSet->currentIndex()+1)+1);
        modifier->initData(totalTime/(1)+1);
        modifier->setAxisZRange(0.0f,totalTime/(1)+1);
    }
    delete mysql;
}


void Login_ECGEEG::on_pb_setting_return_clicked()
{
    ui->tabWidget->setCurrentIndex(1);
    isSaveRawData=ui->checkBox_saveRawData->isChecked();
}


void Login_ECGEEG::on_pb_OpenSerial_clicked()
{
    if(ui->pb_OpenSerial->text()=="刷新串口")
    {
        refresh_serial();
    }else if(ui->pb_OpenSerial->text()=="打开串口")
    {
        QString portName=ui->comboBox_serialPort->currentText();
        if(portName.contains("COM")){
            serialPort->setPortName(portName);
            serialPort->setBaudRate(460800);
            if(serialPort->open(QFileDevice::ReadWrite))
            {
                //设置图片
                ui->pb_OpenSerial->setText("关闭串口");
                ui->label_serialportstate->setStyleSheet(QString("border-image:url(:/new/prefix1/images/msg_info.png);"));
            }

        }else{
            QMessageBox::about(this,"温馨提醒","请先将USBDongle插入电脑U口刷新");
        }
    }else if(ui->pb_OpenSerial->text()=="关闭串口"){
        ui->pb_OpenSerial->setText("打开串口");
        ui->label_serialportstate->setStyleSheet(QString("border-image:url(:/new/prefix1/images/msg_error.png);"));
        serialPort->close();
    }
}

void Login_ECGEEG::on_pb_clearDevice_clicked()
{
    isClear=true;
    if(serialPort->isOpen())
    {
        qDebug()<<"serialPort_CLEAR";
        QString order="AT+CLEAR\r\n";
        serialPort->write(order.toUtf8());

    }else{

    }
}
QString Login_ECGEEG::CharArrayToHexString(QByteArray Buffer,int Len)
{
    QString buf;
    for(int i=0;i<Len;i++){
        QString str = QString("%1").arg(Buffer[i]&0xFF,2,16,QLatin1Char('0')).toUpper() + QString("");   //2 字符宽度
        buf += str;
    }
    return buf;
}
void Login_ECGEEG::readComDataSlot()
{
    QByteArray readComData = serialPort->readAll();

    if(StartCollectFlag && isSaveRawData)
    {
        stream<<CharArrayToHexString(readComData,readComData.size());
        // outFile << readComData.data();
    }
    if(isBind)
    {
        ui->label_serialportreceive->setText("绑定设备："+QString(readComData));
        isBind=false;
        settings->setValue("ECGHOLTERMAC",ui->lineEdit_ECGMac->text());
        settings->setValue("DUALEEGMAC",ui->lineEdit_DualEEGMac->text());
        settings->setValue("OXBRACKETMAC",ui->lineEdit_OxBracketMac->text());
    }
    if(isClear)
    {
        ui->label_serialportreceive->setText("清除设备："+QString(readComData));
        isClear=false;
        settings->setValue("ECGHOLTERMAC","");
        settings->setValue("DUALEEGMAC","");
        settings->setValue("OXBRACKETMAC","");
    }
    double ecgWave[200]={0}; double respWave[200]={0};int ecg_respLen[1]={0};
    double leftEEGWave[200]={0}; double rightEEGWave[200]={0}; double irWave[200]={0}; double appgWave[200]={0};int eeg_ppgLen[1]={0};
    MultiUSBDongle_TransData(reinterpret_cast<unsigned char*>(readComData.data()), readComData.size(), ecgWave, respWave, ecg_respLen, leftEEGWave, rightEEGWave, irWave, appgWave, eeg_ppgLen);

    //qDebug()<<"ecg_respLen="<<ecg_respLen[0];
    for(int i=0;i<ecg_respLen[0];i++){
        if(!isExitCollect){
            mpcs_ecg->Update_Data(isECGOff,ecgWave[i]);
            mpcs_resp->Update_Data(isECGOff,respWave[i]);

        }
    }
    for(int i=0;i<eeg_ppgLen[0];i++){
        if(!isExitCollect){
            mpcs_eeg->Update_Data(isEEGOff,leftEEGWave[i]);
            mpcs_ir->Update_Data(isEEGOff,irWave[i]);
        }
        if(StartCollectFlag)
        {
            ui->progressBar->setValue(SampleNum++);
        }
    }

}

void Login_ECGEEG::on_pb_bindDevice_clicked()
{
    isBind=true;
    QString dualEEGMac=ui->lineEdit_DualEEGMac->text();
    QString ecgMac=ui->lineEdit_ECGMac->text();
    if(dualEEGMac.length()==12 && ecgMac.length()==12)
    {
        if(serialPort->isOpen())
        {
            QString order="AT+SetMac"+dualEEGMac+ecgMac+"\r\n";
            serialPort->write(order.toUtf8());


        }else{

        }
    }

}


void Login_ECGEEG::on_pb_conn_ecg_clicked()
{
    if(serialPort->isOpen())
    {
        if(ui->pb_conn_ecg->text()=="连接心电贴"){
            ui->pb_conn_ecg->setText("断开心电贴");
            serialPort->write(reinterpret_cast<char*>(ecgHolterStartCollectOrder), sizeof(ecgHolterStartCollectOrder));
            isExitCollect=false;
            if(!timer_DeviceState.isActive())
                timer_DeviceState.start();
        }else{
            ui->pb_conn_ecg->setText("连接心电贴");
            serialPort->write(reinterpret_cast<char*>(ecgHolterStopCollectOrder), sizeof(ecgHolterStopCollectOrder));

        }

    }else{
        QMessageBox::about(this,"温馨提示","串口未打开，请点击'采集前配置' 按钮");
    }
}


void Login_ECGEEG::on_pb_conn_eeg_clicked()
{
    if(serialPort->isOpen())
    {
        if(ui->pb_conn_eeg->text()=="连接脑电头带"){
            ui->pb_conn_eeg->setText("断开脑电头带");
            serialPort->write(reinterpret_cast<char*>(dualeegStartCollectOrder), sizeof(dualeegStartCollectOrder));
            isExitCollect=false;
            if(!timer_DeviceState.isActive())
                timer_DeviceState.start();
        }else{
            ui->pb_conn_eeg->setText("连接脑电头带");
            serialPort->write(reinterpret_cast<char*>(dualeegStopCollectOrder), sizeof(dualeegStopCollectOrder));
        }
    }else{
        QMessageBox::about(this,"温馨提示","串口未打开，请点击'采集前配置' 按钮");
    }
}


void Login_ECGEEG::on_pb_measurepage_return_clicked()
{

    if(StartCollectFlag)
    {
        QMessageBox::StandardButton button  = QMessageBox::warning(this, "警告", "当前正在数据采集，您确认要退出吗？",
                                                                  QMessageBox::Yes | QMessageBox::No, QMessageBox::NoButton);
        if (button == QMessageBox::StandardButton::Yes) {
            ExitCollect();
        }
    }else{
        ui->tabWidget->setCurrentIndex(1);
    }


}


void Login_ECGEEG::on_pb_datacollect_start_clicked()
{
    if(ui->pb_datacollect_start->text()=="开始采集")
    {
        isExitCollect=false;
        StartCollectFlag=true;
        stepNum=0;stepIndex=0;
        timerRealTimeIndex.start();
        timerFFT3DAnaShow.start();
        timerForStep.start();
        MultiUSBDongle_setBioEEGOXDevice_Start();
        MultiUSBDongle_setECG_Holter_Device_StartCompute();
        ui->pb_datacollect_start->setText("停止采集");
        getFileName();
        // outFile.open(fileName.toUtf8().constData());

        file.setFileName(fileName);
        if (!file.open(QIODevice::WriteOnly  | QIODevice::Text)) {
            qDebug() << "Failed to open file:" << fileName;
        }
        stream.setDevice(&file);

        QFile file_info;
        file_info.setFileName(fileName_userInfo);
        if (!file_info.open(QIODevice::WriteOnly  | QIODevice::Text)) {
            qDebug() << "Failed to open file:" << fileName_userInfo;
        }
        stream_info.setDevice(&file_info);

        //ui->lineEdit_age->text().toInt(),ui->comboBox->currentIndex()
        stream_info<<ui->lineEdit_age->text().toInt()<<"\r\n";
        stream_info<<ui->comboBox->currentIndex()<<"\r\n";
        stream_info<<settings->value("ECGHOLTERMAC").toString()<<"\r\n";
        stream_info<<settings->value("DUALEEGMAC").toString()<<"\r\n";
        stream_info<<settings->value("OXBRACKETMAC").toString()<<"\r\n";


        for(int i=0;i<switchFlag.size();i++)
        {
            stream_info<<switchFlag.at(i)<<","<<eveyStepTime.at(i)<<"\r\n";
        }

        file_info.close();


        SampleNum=0;
        tartetRow=0;
        if(switchFlag.at(0)==1)
        {
            //第一个阶段是视频
            ui->tabWidget->setCurrentIndex(6);
            m_pPlayer->setSource(resourcePath.at(0));
            audioOutput->setVolume(0.5f);
        }else if(switchFlag.at(0)==2)
        {
            //第一个阶段是音频
            ui->tabWidget->setCurrentIndex(2);
            m_pPlayer->setSource(resourcePath.at(0));
            audioOutput->setVolume(0.5f);
            ui->progressBar->setMinimum(0);
            ui->progressBar->setMaximum(eveyStepTime.at(0)*250);
        }else
        {
            //第一个阶段是常规信号采集
            ui->tabWidget->setCurrentIndex(2);
            ui->progressBar->setMinimum(0);
            ui->progressBar->setMaximum(eveyStepTime.at(0)*250);
        }

    }else if(ui->pb_datacollect_start->text()=="停止采集")
    {
        if(StartCollectFlag)
        {
            QMessageBox::StandardButton button  = QMessageBox::warning(this, "警告", "当前正在数据采集，您确认要退出吗？",
                                                                      QMessageBox::Yes | QMessageBox::No, QMessageBox::NoButton);
            if (button == QMessageBox::StandardButton::Yes) {
                ExitCollect();
            }
        }else{
            ui->tabWidget->setCurrentIndex(1);
        }

    }
}

/**
 * @brief Login_ECGEEG::ExitCollect
 * 中途终止实验需要进行的操作
 */
void Login_ECGEEG::ExitCollect()
{
    isExitCollect=true;
    StartCollectFlag=false;
    timer.start();
    timerRealTimeIndex.stop();
    timerFFT3DAnaShow.stop();
    timerForStep.stop();
    timer_DeviceState.stop();
    ui->pb_datacollect_start->setText("开始采集");
    file.close();

    deleteFile(fileName);
    deleteFile(fileName_design);
    deleteFile(fileName_userInfo);
    if(m_pPlayer->isPlaying())
    {
        m_pPlayer->stop();
    }
    ui->tabWidget->setCurrentIndex(1);
    modifier->initData(totalTime/(ui->comboBox_ffttimeSet->currentIndex()+1)+1);
    ui->progressBar->setValue(0);
    ui->progressBar_video->setValue(0);
    ui->pb_conn_ecg->setText("连接心电贴");
    ui->pb_conn_eeg->setText("连接脑电头带");
    mpcs_ir->clearWave();
    mpcs_ecg->clearWave();
    mpcs_eeg->clearWave();
    mpcs_resp->clearWave();
}

void Login_ECGEEG::deleteFile(QString fileName)
{
    QByteArray bas=fileName.toUtf8();
    if (QFile::exists(bas.constData())) {
        if (QFile::remove(bas.constData())) {
            qDebug() << "文件删除成功！";
        } else {
            qDebug() << "文件删除失败！";
        }
    } else {
        qDebug() << "文件不存在！";
    }
}
/**
 * @brief Login_ECGEEG::Over
 * 正常采集退出
 */
void Login_ECGEEG::Over()
{
    isExitCollect=true;
    StartCollectFlag=false;
    timer.start();
    timerRealTimeIndex.stop();
    timerFFT3DAnaShow.stop();
    timerForStep.stop();
    timer_DeviceState.stop();
    ui->pb_datacollect_start->setText("开始采集");
    file.close();
    if(m_pPlayer->isPlaying())
    {
        m_pPlayer->stop();
    }
    ui->tabWidget->setCurrentIndex(1);
    modifier->initData(totalTime/(ui->comboBox_ffttimeSet->currentIndex()+1)+1);
    ui->progressBar->setValue(0);
    ui->progressBar_video->setValue(0);
    ui->pb_conn_ecg->setText("连接心电贴");
    ui->pb_conn_eeg->setText("连接脑电头带");
    mpcs_ir->clearWave();
    mpcs_ecg->clearWave();
    mpcs_eeg->clearWave();
    mpcs_resp->clearWave();
}
void Login_ECGEEG::stopTrans()
{
    if(stopNum==0)
    {
        if(serialPort->isOpen())
        {
            serialPort->write(reinterpret_cast<char*>(dualeegStopCollectOrder), sizeof(dualeegStopCollectOrder));

        }
    }else if(stopNum==1)
    {
        if(serialPort->isOpen())
        {
            serialPort->write(reinterpret_cast<char*>(ecgHolterStopCollectOrder), sizeof(ecgHolterStopCollectOrder));
        }
    }
    stopNum++;
    if(stopNum==2)
    {
        stopNum=0;
        timer.stop();
    }
}
void Login_ECGEEG::updateDeviceState()
{
    unsigned char isDualEEGExist=MultiUSBDongle_getBioEEGOXDevice_IsExist();
    unsigned char isECGExist=MultiUSBDongle_getECG_HolterDevice_IsExist();
    setConnectState(ui->label_ecg_state,isECGExist==1);
    setConnectState(ui->label_eeg_state,isDualEEGExist==1);
    serialPort->write(reinterpret_cast<char*>(ecgHolterInfoOrder), sizeof(ecgHolterInfoOrder));
    if(isDualEEGExist && isECGExist)
    {
        ui->pb_datacollect_start->setEnabled(true);
    }

}
void Login_ECGEEG::updateIndex()
{
    isEEGOff=MultiUSBDongle_getBioEEGOXDevice_EleOFF()==1;
    int eeg_ele=MultiUSBDongle_getBioEEGOXDevice_Electricity();
    int ecg_ele=MultiUSBDongle_getECG_Holter_Device_Electricity();
    // ui->progressBar_ecg_ele->setValue(ecg_ele);
    ui->progressBar_ecg_ele->setValue(55);
    ui->progressBar_eeg_ele->setValue(eeg_ele);
    isECGOff= MultiUSBDongle_getECG_Holter_Device_EleOff()==1;
    float ppgIndex[5]={0};
    MultiUSBDongle_getBioEEGOXDevice_HROXRealTimeIndex(ppgIndex);
    if(ppgIndex[0]>0)
    {
        if(!isEEGOff)
            ui->label_pr->setText("脉率："+QString::number(ppgIndex[0]));
        else
            ui->label_pr->setText("脉率：--");
    }
    if(ppgIndex[1]>0)
    {
        if(!isEEGOff)
            ui->label_spox->setText("血氧："+QString::number(ppgIndex[1]));
        else
            ui->label_spox->setText("血氧：--");
    }
    unsigned char realTimeIndex[2]= {0};
    MultiUSBDongle_getECG_Holter_Device_RealTimeIndex(realTimeIndex);
    if(realTimeIndex[0]>0)
    {
        if(!isECGOff)
            ui->label_hr->setText("心率："+QString::number(realTimeIndex[0]));
        else
            ui->label_hr->setText("心率：--");
    }
    if(realTimeIndex[1]>0){
        if(!isECGOff)
            ui->label_resprate->setText("呼吸率："+QString::number(realTimeIndex[1]));
        else
            ui->label_resprate->setText("呼吸率：--");
    }




}
void Login_ECGEEG::onStepShow()
{
    qDebug()<<"stepNum=="<<stepNum<<",stepTimeDuration"<<stepIndex<<"="<<stepTimeDuration.at(stepIndex);
    int totalNum=switchFlag.size();//共有多少个阶段
    if(stepNum==stepTimeDuration.at(stepIndex)){
        stepIndex++;
        if(stepIndex==totalNum)
        {
            //结束测量
            Over();
        }else{
            if(switchFlag.at(stepIndex)==1)
            {
                ui->tabWidget->setCurrentIndex(6);
                m_pPlayer->stop();
                m_pPlayer->setSource(resourcePath.at(stepIndex));
            }else if(switchFlag.at(stepIndex)==2)
            {
                m_pPlayer->stop();
                m_pPlayer->setSource(resourcePath.at(stepIndex));
                ui->tabWidget->setCurrentIndex(2);
            }else
            {
                ui->tabWidget->setCurrentIndex(2);
                m_pPlayer->stop();
                //设置常规采集（静态采集时间）
                ui->progressBar->setMinimum(0);
                ui->progressBar->setMaximum(eveyStepTime.at(stepIndex)*250);
                ui->progressBar->setValue(0);
            }
        }
    }
    ui->label_info->setText("实验名称："+ui->comboBox_designsele->currentText()+",共有"+QString::number(totalNum)+"个阶段,当前处于试验阶段"+QString::number(stepIndex+1));
    ui->label_video_info->setText("实验名称："+ui->comboBox_designsele->currentText()+",共有"+QString::number(totalNum)+"个阶段,当前处于试验阶段"+QString::number(stepIndex+1));
    stepNum++;
}
void Login_ECGEEG::onFFTAnaShow()
{
    if(!isEEGOff){
        double eegIndex[13];
        double f[100];
        double psd[100];
        MultiUSBDongle_getBioEEGOXDevice_BrainWaveIndex(eegIndex,f,psd);
        QSurfaceDataRow *newRow = new QSurfaceDataRow;
        for (int x = 0; x < 80; x++) {
            if(maxFFTMag<psd[x]){
                maxFFTMag=psd[x];
                if(isAutoAdjugeY){
                    ui->lineEdit_minY->setText(QString::number(0,'f',1));
                    ui->lineEdit_maxY->setText(QString::number(maxFFTMag,'f',2));
                    modifier->setAxisYRange(0,maxFFTMag);
                }

            }
            *newRow << QSurfaceDataItem(QVector3D(x, psd[x], tartetRow));  // 修改y值
        }
        modifier->setData(tartetRow,newRow);
        tartetRow++;
    }

}
void Login_ECGEEG::on_comboBox_timeSet_currentIndexChanged(int index)
{
    qDebug()<<"on_comboBox_timeSet_currentIndexChanged"<<"index="<<index;
}

void Login_ECGEEG::getFileName()
{
    QDateTime Time = QDateTime::currentDateTime();
    QString MeasureTime=Time.toString("yyyyMMdd_hhmmss");//格式化时间
    QString ParentFolder=ui->lineEdit_SaveDataPath->text()+"/"+ui->comboBox_designsele->currentText()+"/"+ui->lineEdit->text();
    qDebug()<<"ParentFolder="<<ParentFolder;
    QDir dir(ParentFolder);

    if(dir.exists())
    {
        qDebug()<<"dir.exists()";
        fileName=ParentFolder+"/"+MeasureTime+".txt";
        fileName_userInfo=ParentFolder+"/"+"UserInfo.txt";
        fileName_design=ParentFolder+"/"+"DesignInfo.txt";
    }else
    {
        bool ok = dir.mkpath(ParentFolder);//创建多级目录
        if(ok)
        {
            qDebug()<<"创建多级目录成功";
            // QString fileName = QString::fromUtf8("测试文件.txt");
            fileName= ParentFolder+"/"+MeasureTime+".txt";
            fileName=QString::fromUtf8(fileName.toLatin1());
            qDebug()<<"fileName="<<fileName;
            fileName_userInfo=ParentFolder+"/"+"UserInfo.txt";
            fileName_design=ParentFolder+"/"+"DesignInfo.txt";
        }
    }
}




void Login_ECGEEG::on_pb_login_close_clicked()
{
    this->close();
}


void Login_ECGEEG::on_pb_historypage_return_clicked()
{
    ui->tabWidget->setCurrentIndex(1);
}


void Login_ECGEEG::on_pb_designpage_return_clicked()
{
    ui->tabWidget->setCurrentIndex(1);
}


void Login_ECGEEG::on_checkBox_ShadowShow_stateChanged(int arg1)
{
    modifier->toggleShadows(arg1==2);
}


void Login_ECGEEG::on_checkBox_drawWire_stateChanged(int arg1)
{
    modifier->toggleSeeThrough(arg1==2);
}


void Login_ECGEEG::on_lineEdit_minY_textChanged(const QString &arg1)
{
    float min=ui->lineEdit_minY->text().toFloat();
    float max=ui->lineEdit_maxY->text().toFloat();
    if(min<max)
    {
        modifier->setAxisYRange(min,max);
    }
}


void Login_ECGEEG::on_checkBox_AdjustY_stateChanged(int arg1)
{
    ui->lineEdit_maxY->setEnabled(arg1==0);
    ui->lineEdit_minY->setEnabled(arg1==0);
    isAutoAdjugeY=arg1==2;
    if(arg1==0){
        float min=ui->lineEdit_minY->text().toFloat();
        float max=ui->lineEdit_maxY->text().toFloat();
        if(min<max)
        {
            modifier->setAxisYRange(min,max);
        }
    }else if(arg1==2)
    {
        modifier->setAxisYRange(0,maxFFTMag);
        ui->lineEdit_minY->setText("0.0");
        ui->lineEdit_maxY->setText(QString::number(maxFFTMag,'f',2));
    }

}


void Login_ECGEEG::on_lineEdit_maxY_textChanged(const QString &arg1)
{
    float min=ui->lineEdit_minY->text().toFloat();
    float max=ui->lineEdit_maxY->text().toFloat();
    if(min<max)
    {
        modifier->setAxisYRange(min,max);
    }
}




void Login_ECGEEG::on_pb_configOver_clicked()
{
    ui->tabWidget->setCurrentIndex(1);
    isSaveRawData=ui->checkBox_saveRawData->isChecked();

}


void Login_ECGEEG::on_pb_designOver_clicked()
{
    if(ui->lineEdit_designName->text().length()>0)
    {
        int rows=m_pTableModel->rowCount();
        if(rows>0){
            m_pPlayer->stop();
            MySql *mySql = new MySql(cglobal::DataBasePath);
            if(!mySql->DesignDataQueryBy(ui->lineEdit_designName->text()))
            {
                QJsonArray jsonArray;
                designDataBean ddb;
                ddb.name=ui->lineEdit_designName->text();
                ddb.LeverNum=rows;
                QJsonObject jsonObject;
                for(int i=0;i<rows;i++)
                {
                    QJsonObject jsonObject1;
                    QModelIndex index_Type = m_pTableModel->index(i, COLUMN_TYPE);
                    jsonObject1.insert("Type",m_pTableModel->data(index_Type).toString());
                    QModelIndex index_Time = m_pTableModel->index(i, COLUMN_TIME);
                    jsonObject1.insert("Time",m_pTableModel->data(index_Time).toString());
                    QModelIndex index_PATH = m_pTableModel->index(i, COLUMN_PATH);
                    jsonObject1.insert("Path",m_pTableModel->data(index_PATH).toString());
                    QModelIndex index_SOURCETYPE = m_pTableModel->index(i, COLUMN_SOURCETYPE);
                    jsonObject1.insert("SourceType",m_pTableModel->data(index_SOURCETYPE).toString());
                    jsonArray.append(jsonObject1);
                }
                jsonObject.insert("jsonArray",jsonArray);
                QString s=QString(QJsonDocument(jsonObject).toJson());
                ddb.content=s;
                if(!mySql->DesignDataInsert(ddb))
                {
                    QMessageBox::about(this,"温馨提示","添加项目失败");
                }else{
                    ui->tabWidget->setCurrentIndex(1);
                }

            }else{
                QMessageBox::about(this,"温馨提示","该项目已经存在，请重新修改项目名称");
            }
            delete mySql;


        }else
        {
             QMessageBox::about(this,"温馨提示","请至少添加一个项目（常态或者刺激态）！！！");
        }

    }else{
        QMessageBox::about(this,"温馨提示","请为项目添加一个名称！！！");
    }

}

void Login_ECGEEG::initTableWidget()
{
    TableViewHeader *m_pTableHeader_All= new TableViewHeader(Qt::Horizontal, this);//表头
    m_pTableHeader_All->setStretchLastSection(true);//表头最后一列填充
    ui->tableView->setHorizontalHeader(m_pTableHeader_All);//设置表头

    //创建model（目前使用的是标准数据模型，可以自定义数据模型），绑定model
    m_pTableModel = new QStandardItemModel(this);
    ui->tableView->setModel(m_pTableModel);//设置model
    ui->tableView->verticalHeader()->hide();


    //创建表头信息
    QStringList headerList;
    ui->tableView->horizontalHeader()->setSectionsClickable(false);

    headerList << tr("No.")   << tr("类型")<<tr("时长")<< tr("资源路径") << tr("资源类型");
    m_pTableModel->setHorizontalHeaderLabels(headerList);

    //设置列宽
    setColumnWidth();
}

void Login_ECGEEG::initTableWidget_sel()
{
    TableViewHeader *m_pTableHeader_All= new TableViewHeader(Qt::Horizontal, this);//表头
    m_pTableHeader_All->setStretchLastSection(true);//表头最后一列填充
    ui->tableView_sel->setHorizontalHeader(m_pTableHeader_All);//设置表头

    //创建model（目前使用的是标准数据模型，可以自定义数据模型），绑定model
    m_pTableModel_sel = new QStandardItemModel(this);
    ui->tableView_sel->setModel(m_pTableModel_sel);//设置model
    ui->tableView_sel->verticalHeader()->hide();


    //创建表头信息
    QStringList headerList;
    ui->tableView_sel->horizontalHeader()->setSectionsClickable(false);

    headerList << tr("No.")   << tr("类型")<<tr("时长")<< tr("资源路径") << tr("资源类型");
    m_pTableModel_sel->setHorizontalHeaderLabels(headerList);

    //设置列宽
    setColumnWidth_sel();
}
/*************************
 * QTableView-设置列宽
 * ***********************/
void Login_ECGEEG::setColumnWidth()
{
    ui->tableView->setColumnWidth(COLUMN_NO,80);
    ui->tableView->setColumnWidth(COLUMN_TYPE, 80);
    ui->tableView->setColumnWidth(COLUMN_TIME, 120);
    ui->tableView->setColumnWidth(COLUMN_PATH, 550);
    ui->tableView->setColumnWidth(COLUMN_SOURCETYPE, 50);

}
void Login_ECGEEG::setColumnWidth_sel()
{
    ui->tableView_sel->setColumnWidth(COLUMN_NO,50);
    ui->tableView_sel->setColumnWidth(COLUMN_TYPE, 50);
    ui->tableView_sel->setColumnWidth(COLUMN_TIME, 120);
    ui->tableView_sel->setColumnWidth(COLUMN_PATH, 480);
    ui->tableView_sel->setColumnWidth(COLUMN_SOURCETYPE, 50);

}
void Login_ECGEEG::on_pb_routineAdd_clicked()
{
    int rowcount = m_pTableModel->rowCount();
    qDebug()<<"rowcount="<<rowcount;
    m_pTableModel->insertRow(rowcount, QModelIndex());
    m_pTableModel->setData(m_pTableModel->index(rowcount, COLUMN_NO), rowcount+1);
    m_pTableModel->setData(m_pTableModel->index(rowcount, COLUMN_TYPE), "常态");
    m_pTableModel->setData(m_pTableModel->index(rowcount, COLUMN_TIME), ui->comboBox_timeSet->currentText());
    m_pTableModel->setData(m_pTableModel->index(rowcount, COLUMN_PATH), "");
    m_pTableModel->setData(m_pTableModel->index(rowcount, COLUMN_SOURCETYPE), "");
    // 设置全部列居中显示
    for(int j = 0; j < 5; j++)
    {
        m_pTableModel->item(rowcount, j)->setTextAlignment(Qt::AlignCenter);
    }

}





void Login_ECGEEG::on_checkBox_video_toggled(bool checked)
{
    ui->checkBox_sound->setChecked(!checked);
}


void Login_ECGEEG::on_checkBox_sound_toggled(bool checked)
{
    ui->checkBox_video->setChecked(!checked);
}



void Login_ECGEEG::on_pb_fileSelect_clicked()
{

    if(ui->checkBox_video->isChecked()){
        selFileName = QFileDialog::getOpenFileName(
            this,
            tr("选择视频文件"),
            QDir::currentPath(),
            tr("视频 (*.MP4 *.mp4)")
            );
    }else{
        selFileName = QFileDialog::getOpenFileName(
            this,
            tr("选择音频文件"),
            QDir::currentPath(),
            tr("视频 (*.MP3 *.mp3)")
            );


    }
    ui->lineEdit_filePath->setText(selFileName);
    qDebug()<<"selFileName="<<selFileName;
    QByteArray encodedPath = selFileName.toLocal8Bit();
    const char* cPath = encodedPath.constData();

    QString qtPath = QString::fromStdWString(selFileName.toStdWString());

    // 尝试使用转换后的路径
    // m_pPlayer->setSource(QUrl::fromLocalFile(QString::fromLocal8Bit(cPath)));
    m_pPlayer->setSource(QUrl::fromLocalFile(qtPath));
    // m_pPlayer->play();
}


void Login_ECGEEG::on_pb_cijiAdd_clicked()
{
    if(!selFileName.isEmpty())
    {
        int rowcount = m_pTableModel->rowCount();
        qDebug()<<"rowcount="<<rowcount;
        m_pTableModel->insertRow(rowcount, QModelIndex());
        m_pTableModel->setData(m_pTableModel->index(rowcount, COLUMN_NO), rowcount+1);
        m_pTableModel->setData(m_pTableModel->index(rowcount, COLUMN_TYPE), "刺激");
        if(ui->checkBox_video_len->isChecked())
            m_pTableModel->setData(m_pTableModel->index(rowcount, COLUMN_TIME), selVideoTime);
        else
            m_pTableModel->setData(m_pTableModel->index(rowcount, COLUMN_TIME), ui->comboBox_videotimeSet->currentText());
        m_pTableModel->setData(m_pTableModel->index(rowcount, COLUMN_PATH), selFileName);
        m_pTableModel->setData(m_pTableModel->index(rowcount, COLUMN_SOURCETYPE), ui->checkBox_video->isChecked()?"视频":"音频");
        // 设置全部列居中显示
        for(int j = 0; j < 5; j++)
        {
            m_pTableModel->item(rowcount, j)->setTextAlignment(Qt::AlignCenter);
        }

        // ui->tabWidget->setCurrentIndex(6);

    }else{

    }
}

void Login_ECGEEG::Mplayer_State(QMediaPlayer::MediaStatus enumState)
{
    if (enumState == QMediaPlayer::LoadedMedia) {
        qint64 duration = m_pPlayer->duration();
        qDebug() << "Video duration:" << duration << "ms";
        int hours = duration / (1000 * 3600);
        int minutes = (duration % (1000 * 3600)) / (1000 * 60);
        int seconds = (duration % (1000 * 60)) / 1000;
        if(hours>0)
        {
            selVideoTime=QString::number(hours)+"时"+QString::number(minutes)+"分"+QString::number(seconds)+"秒";
        }else
        {
            if(minutes>0)
            {
                selVideoTime=QString::number(minutes)+"分"+QString::number(seconds)+"秒";
            }else{
                selVideoTime=QString::number(seconds)+"秒";
            }
        }

        ui->label_videoLen->setText("资源时长:"+selVideoTime);
    }

}

void Login_ECGEEG::OnDurationChanged(qint64 i64Duration)
{
    qDebug()<<"OnDurationChanged"<<i64Duration;
    ui->progressBar_video->setMaximum(i64Duration);
    ui->progressBar_video->setMinimum(0);
    m_pPlayer->play();
}

void Login_ECGEEG::OnSlider(qint64 p)
{
    ui->progressBar_video->setValue(p);
}


void Login_ECGEEG::on_comboBox_realtimeAnaSet_currentIndexChanged(int index)
{
    timerRealTimeIndex.setInterval((index+1)*1000);
    settings->setValue("realtimeAnaInterval",(index+1)*1000);

}




void Login_ECGEEG::on_comboBox_ffttimeSet_currentIndexChanged(int index)
{
    settings->setValue("ffttimeAnaInterval",(index+1)*1000);
    timerFFT3DAnaShow.setInterval((index+1)*1000);
}


void Login_ECGEEG::on_pb_clearDesign_clicked()
{
    int rowCount = m_pTableModel->rowCount();
    if (rowCount > 0)
        m_pTableModel->removeRows(0, rowCount); // 从第 0 行开始删除所有行
}


void Login_ECGEEG::on_checkBox_video_len_toggled(bool checked)
{
    ui->checkBox_video_len_dead->setChecked(!checked);
    ui->comboBox_videotimeSet->setEnabled(!checked);

}


void Login_ECGEEG::on_checkBox_video_len_dead_toggled(bool checked)
{
    ui->checkBox_video_len->setChecked(!checked);
    ui->comboBox_videotimeSet->setEnabled(checked);
}


void Login_ECGEEG::on_comboBox_designsele_currentTextChanged(const QString &arg1)
{
    if(!isfirst)
    {
        totalTime=0;
        MySql *mysql=new MySql(cglobal::DataBasePath);
        designDataBean ddb;
        if(mysql->DesignDataSelect(arg1,ddb))
        {
            int rowCount = m_pTableModel_sel->rowCount();
            if (rowCount > 0)
                m_pTableModel_sel->removeRows(0, rowCount); // 从第 0 行开始删除所有行
            QList<DesignData> dds=getDesignData(ddb.content);//显示最近创建的任务
            int len=dds.size();
            stepTimeDuration.clear();switchFlag.clear();resourcePath.clear();eveyStepTime.clear();
            for(int k=0;k<len;k++)
            {
                m_pTableModel_sel->insertRow(k, QModelIndex());
                m_pTableModel_sel->setData(m_pTableModel_sel->index(k, COLUMN_NO), k+1);
                m_pTableModel_sel->setData(m_pTableModel_sel->index(k, COLUMN_TYPE), dds.at(k).Type);
                m_pTableModel_sel->setData(m_pTableModel_sel->index(k, COLUMN_TIME), dds.at(k).durationtimes);
                int c_steptime=convertTimeStringToSeconds(dds.at(k).durationtimes);
                totalTime+=c_steptime;
                stepTimeDuration.push_back(totalTime);
                eveyStepTime.push_back(c_steptime);
                m_pTableModel_sel->setData(m_pTableModel_sel->index(k, COLUMN_PATH), dds.at(k).resourcePath);
                resourcePath.push_back(dds.at(k).resourcePath);
                m_pTableModel_sel->setData(m_pTableModel_sel->index(k, COLUMN_SOURCETYPE), dds.at(k).resourceType);
                if(dds.at(k).resourceType=="视频")
                    switchFlag.push_back(1);
                else if(dds.at(k).resourceType=="音频")
                    switchFlag.push_back(2);
                else
                    switchFlag.push_back(0);
                // 设置全部列居中显示
                for(int j = 0; j < 5; j++)
                {
                    m_pTableModel_sel->item(k, j)->setTextAlignment(Qt::AlignCenter);
                }
            }
            // modifier->setAxisZRange(0.0f,totalTime/(ui->comboBox_ffttimeSet->currentIndex()+1)+1);
            modifier->initData(totalTime/(ui->comboBox_ffttimeSet->currentIndex()+1)+1);
            modifier->setAxisZRange(0.0f,totalTime/(ui->comboBox_ffttimeSet->currentIndex()+1)+1);
        }
        delete mysql;

    }
    isfirst=false;
}


void Login_ECGEEG::on_pb_deleteDesign_clicked()
{

    QMessageBox::StandardButton button  = QMessageBox::warning(this, "警告", "您确认删除该方案吗？",
                                                              QMessageBox::Yes | QMessageBox::No, QMessageBox::NoButton);
    if (button == QMessageBox::StandardButton::Yes) {
        MySql *mysql=new MySql(cglobal::DataBasePath);
        if(mysql->DesignDataDelete(ui->comboBox_designsele->currentText()))
        {
            ui->comboBox_designsele->removeItem(ui->comboBox_designsele->currentIndex());
        }
    }


}




int Login_ECGEEG::convertTimeStringToSeconds(const QString &timeStr) {
    // 定义正则表达式，匹配时、分、秒部分（允许部分省略）
    QRegularExpression regex(
        "(?:^(\\d+)时)?"
        "(?:^(\\d+)分|(?:.*?(\\d+)分))?"
        "(?:^(\\d+)秒|(?:.*?(\\d+)秒))?$"
        );

    QRegularExpressionMatch match = regex.match(timeStr);

    // 提取时、分、秒数值（未匹配部分默认为0）
    int hours = match.captured(1).toInt();
    int minutes = match.captured(2).isEmpty()  ? match.captured(3).toInt()  : match.captured(2).toInt();
    int seconds = match.captured(4).isEmpty()  ? match.captured(5).toInt()  : match.captured(4).toInt();

    return hours * 3600 + minutes * 60 + seconds;
}

void Login_ECGEEG::on_pb_Vidio_Stop_clicked()
{
    //终止实验
    ExitCollect();
}


void Login_ECGEEG::on_horizontalSlider_volume_sliderMoved(int position)
{
    audioOutput->setVolume((float)position/100.0);
}

void Login_ECGEEG::setConnectState(QLabel*lable,bool b)
{
    if(b)
        lable->setStyleSheet("QLabel  { border-image: url(':/new/prefix1/images/bt_connect2.png');  }");
    else
        lable->setStyleSheet("QLabel  { border-image: url(':/new/prefix1/images/bt_disconnect.png');  }");

}

void Login_ECGEEG::on_pb_browse_clicked()
{
    QString folderPath = QFileDialog::getExistingDirectory(
        nullptr, // 父窗口
        "选择文件夹", // 对话框标题
        QDir::homePath(), // 默认打开的路径（这里设置为用户的主目录）
        QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks // 选项
        );

    // 输出用户选择的文件夹路径
    if (!folderPath.isEmpty())  {
        qDebug() << "选择的文件夹路径：" << folderPath;
        ui->lineEdit_SaveDataPath->setText(folderPath);
        settings->setValue("SaveRawPath",folderPath);
    } else {
        qDebug() << "未选择文件夹";
    }
}


void Login_ECGEEG::on_pb_history_selectfile_clicked()
{


}

